#!/bin/bash

# 使用方法
# ./install.sh org/codehaus/groovy/groovy-jsr223/2.5.13
# ./install.sh groupId artifactId version [packaging=jar]

groupId=$1
artifactId=$2
version=$3
packaging=${4-"jar"}

auto_parse() {
  if [[ -z "$artifactId" ]]; then
    echo "./install.sh $groupId" >> "./install-dependency.sh"
    str=${groupId//\//,}
    infos=(${str//,/ })
    echo ${infos[@]}
  else
    echo ""
  fi
}

show_install_info() {
  echo "<groupId>$groupId</groupId>"
  echo "<artifactId>$artifactId</artifactId>"
  echo "<version>$version</version>"
  echo "<packaging>$packaging</packaging>"
}

need_sure=$(auto_parse) || exit 1
if [[ -n "$need_sure" ]]; then
  jar=${need_sure% *}

  groupId=${jar% *}
  groupId=${groupId// /.}

  artifactId=${jar:${#groupId}+1}
  version=${need_sure##* }
fi

jar_file="$artifactId-$version.$packaging"
jar_url="https://maven.aliyun.com/nexus/content/groups/public/${groupId//./\/}/$artifactId/$version/$jar_file"
show_install_info && echo "install from : $jar_url"

#if [[ -n "$need_sure" ]]; then
#  read -r -p "Are You Sure? [y/n] " input
#  if [[ "$input" != "y" ]]; then
#    echo "exit with not"
#    exit 1
#  fi
#fi

wget $jar_url || exit 1
mvn install:install-file \
-Dfile=$jar_file \
-DgroupId=$groupId \
-DartifactId=$artifactId \
-Dversion=$version \
-Dpackaging=$packaging

rm -f "./$artifactId-$version.$packaging"
echo "==install success=="
show_install_info
